package middleware

import (
	"ginApi/comm"
	"ginApi/model"
	"ginApi/service"
	"github.com/gin-gonic/gin"
)

func AccessRequired(s service.TokenService) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token, _ := ctx.Params.Get("token")

		if token != "" {
			entity := s.GetToken(token)
			if entity != nil && entity.Status == model.TokenStatusValid {
				ctx.Set("user_id", entity.UserId)
				ctx.Set("user_type", entity.UserType)
				ctx.Next()
				return
			}
		}

		comm.Fail(ctx, comm.ErrorTokenNotSet, "需要登录")
		ctx.Abort()
	}
}
